<template>
    <van-uploader 
        :modelValue="modelValue" 
        @update:modelValue="emits('update:modelValue', $event)" 
        :readonly="readonly"
        :deletable="!readonly"
        :max-count="maxCount" 
        :upload-text="uploadText" 
        :before-delete="beforeDelete(uploadField)"
        :before-read="beforeRead" 
        :after-read="afterRead(uploadField)"
    />
</template>

<script lang="ts" setup>
    import { markRaw, reactive, ref, toRaw, onMounted } from 'vue'
    import type { Ref } from 'vue'
    import { showDialog, showLoadingToast, closeToast, showFailToast  } from 'vant'
    import { fileUploadBase64ExApi, idOrcApi } from '@/apis'
    import { compressImg, isCardID } from '@/utils/utils.js'

    const props = withDefaults(defineProps<{
        modelValue?: Array<any>,
        readonly?: boolean,
        maxCount?: number,
        uploadText?: string,
        uploadField?: string,
        formData?: any,
    }>(), {
        modelValue: () => [],
        readonly: false,
        maxCount: 1,
        uploadText: '',
        uploadField: '',
        formData: {},
    })
    const emits = defineEmits<{
        (e:'update:modelValue', data: any): void
        (e:'update:formData', data: any): void
    }>()

    const beforeDelete = (data) => {
        return (file, detail) => {
            let myarr1 = props.formData[data].split(',')
            myarr1.splice(detail.index, 1)
            // props.formData[data] = myarr1.join(',')
            let myobj1 = JSON.parse(JSON.stringify(props.formData))
            myobj1[data] = myarr1.join(',')
            emits('update:formData', myobj1)
            return true
        }
    }
    const beforeRead = (file) => {
        console.log(file)
        if (file.type !== 'image/jpeg' && file.type !== 'image/png') {
            showFailToast('请上传 jpg/png 格式图片');
            return false;
        }
        return true;
    }
    const afterRead = (imgField, isIdOrc = false) => {
        return file => {
            file.status = 'uploading';
            file.message = '上传中...';
            // 执行压缩图片并上传
            let obj = new compressImg(file, afterRead2, imgField, isIdOrc, file )
            // console.log(obj)
            // console.log(obj.getMyf())
            // console.log(obj.getMyfb())
            // console.log(obj.myf)
            // console.log(obj.myfb)
        }
    }
    // 组件方法 获取 流
    const afterRead2 = (imgField, isIdOrc, file, obj) => {
        // failed done 
        // file.status = 'uploading';
        // file.message = '上传中...';
        // file.file: 文件 file.content: base64图片
        console.log(file)
        // let f = new FormData()
        // f.append('file', file.file)
        

        fileUploadBase64ExApi({
            data: obj,
            sCode: 'kmxbyg'
        }).then(res => {
            // file.status = 'done';
            // file.message = '上传完成';
            console.log(res)

            if (imgField == 'sh_ex36' || imgField == 'sh_ex37') {
                // 拍照识按钮要显示不能设置maxCount=1，不然上传一张图就没了按钮
                if (props.modelValue.length > 1) {
                    let myarr2 = JSON.parse(JSON.stringify(props.modelValue))
                    myarr2.shift()
                    emits('update:modelValue', myarr2)
                    
                }
                // props.formData[imgField] = res[0].url
                let myobj2 = JSON.parse(JSON.stringify(props.formData))
                myobj2[imgField] = res[0].url
                emits('update:formData', myobj2)
                // 用过拍照识别后续上传身份证都要进行idOrc验证信息
                if (isIdOrc) {
                    idOrcApi({
                        img: obj
                    }).then(res => {
                        if (res.idcard_number_type == 1) {
                            let obj = res.words_result

                            let myobj3 = JSON.parse(JSON.stringify(props.formData))
                            if (imgField == 'sh_ex36') {
                                // props.formData.sh_ex1 = obj['姓名'].words
                                // props.formData.sh_ex2 = obj['公民身份号码'].words
                                // props.formData.sh_ex3 = obj['性别'].words
                                myobj3.sh_ex1 = obj['姓名'].words
                                myobj3.sh_ex2 = obj['公民身份号码'].words
                            } else if (imgField == 'sh_ex37') {
                                // props.formData.sh_ex5 = obj['姓名'].words
                                // props.formData.sh_ex35 = obj['公民身份号码'].words
                                myobj3.sh_ex5 = obj['姓名'].words
                                myobj3.sh_ex35 = obj['公民身份号码'].words
                            }
                            emits('update:formData', myobj3)
                        } else {
                            throw new Error('身份证验证失败')
                        }
                        file.status = 'done';
                        file.message = '上传完成';
                        
                    }).catch(err => {
                        console.log(err)
                        showFailToast('识别失败')
                        file.status = 'done';
                        file.message = '上传完成';
                    })
                } else {
                    file.status = 'done';
                    file.message = '上传完成';
                }

            } else {
                let myobj4 = JSON.parse(JSON.stringify(props.formData))
                // props.formData[imgField] = res[0].url
                if (props.formData[imgField]) {
                    // props.formData[imgField] = props.formData[imgField].concat(',', res[0].url)
                    myobj4[imgField] = props.formData[imgField].concat(',', res[0].url)
                    
                } else {
                    // props.formData[imgField] = props.formData[imgField].concat(res[0].url)
                    myobj4[imgField] = props.formData[imgField].concat(res[0].url)
                }
                emits('update:formData', myobj4)
                file.status = 'done';
                file.message = '上传完成';
            }
            
        }).catch(err => {
            file.status = 'failed';
            file.message = '上传失败';
            let myarr3 = JSON.parse(JSON.stringify(props.modelValue))
            myarr3[imgField].pop()
            emits('update:modelValue', myarr3)
            showFailToast('上传失败')
            console.log(err)
        })
    }
</script>

<style lang="scss" scoped>
    .uploader-box {
        border-bottom: 1px solid #999999;
        margin: 6px 15px;
        box-sizing: border-box;
        padding: 0px 0;
        height: 180px;
        overflow: hidden;
        img {
            width: 345px;
            height: 180px;
        }
        // 上传图片后图片大小
        :deep(.van-uploader__preview-image) {
            width: 345px;
            height: 180px;
        }
    }
</style>